<template>
  <Card>
    <Form layout="inline" :label-col="{ span: 10 }">
      <FormItem label="一级分类">
        <Select v-model:value="category1Id" class="!w-200px" placeholder="请选择一级分类">
          <SelectOption v-for="c1 in category.category1List" :key="c1.id" :value="c1.id">
            {{ c1.name }}
          </SelectOption>
        </Select>
      </FormItem>

      <FormItem label="二级分类">
        <Select v-model:value="category2Id" class="!w-200px" placeholder="请选择二级分类">
          <SelectOption v-for="c2 in category.category2List" :key="c2.id" :value="c2.id">
            {{ c2.name }}
          </SelectOption>
        </Select>
      </FormItem>

      <FormItem label="三级分类">
        <Select v-model:value="category.category3Id" class="!w-200px" placeholder="请选择三级分类">
          <SelectOption v-for="c3 in category.category3List" :key="c3.id" :value="c3.id">
            {{ c3.name }}
          </SelectOption>
        </Select>
      </FormItem>
    </Form>
  </Card>
</template>

<script lang="ts">
  import { defineComponent } from 'vue';
  export default defineComponent({
    name: 'CategorySelector',
  });
</script>

<script lang="ts" setup>
  import { reactive, onMounted, computed } from 'vue';
  import { Card, Form, FormItem, Select, SelectOption } from 'ant-design-vue';
  import {
    getCategory1ListApi,
    getCategory2ListApi,
    getCategory3ListApi,
  } from '/@/api/product/category';
  import { CategoryDataModel } from './types';

  const category = reactive<CategoryDataModel>({
    // 收集数据
    category1Id: undefined,
    category2Id: undefined,
    category3Id: undefined,
    // 展示数据
    category1List: [],
    category2List: [],
    category3List: [],
  });

  // 一上来请求一级分类列表
  onMounted(async () => {
    category.category1List = await getCategory1ListApi();
  });

  const category1Id = computed({
    get() {
      return category.category1Id;
    },
    async set(category1Id: number) {
      // 点击一级分类列表请求二级分类列表
      category.category1Id = category1Id;
      category.category2List = await getCategory2ListApi(category1Id);
      // 清空
      category.category2Id = undefined;
      category.category3Id = undefined;
      category.category3List = [];
    },
  });

  const category2Id = computed({
    get() {
      return category.category2Id;
    },
    async set(category2Id: number) {
      // 点击二级分类列表请求三级分类列表
      category.category2Id = category2Id;
      category.category3List = await getCategory3ListApi(category2Id);
      category.category3Id = undefined;
    },
  });
</script>
